﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
using System.IO;
using RoadTeam.FineFile.Model;
using System.Xml;

namespace RoadTeam.FineFile.Code
{
    public class GetFileInfo
    {
        public static DataTable ReadEcxelData(String FilePath)
        {
            //根据路径打开一个Excel文件并将数据填充到ds中
            string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source = " + FilePath + ";Extended Properties ='Excel 8.0;HDR=YES;IMEX=1'";
            OleDbConnection conn = new OleDbConnection(strConn);
            conn.Open();
            string strExcel = "";
            OleDbDataAdapter myCommand = null;
            DataTable dtSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
            //包含excel中表名的字符串数组
            string[] strTableNames = new string[dtSheetName.Rows.Count];

            String TableName = String.Empty;

            DataTable ReturnDt = new DataTable();

            for (int k = 0; k < dtSheetName.Rows.Count; k++)
            {
                DataTable dt = new DataTable();
                //我是倒序插入到strTableNames中，因为dtSheetName中行是从后往前读sheet页的
                TableName = dtSheetName.Rows[dtSheetName.Rows.Count - k - 1]["TABLE_NAME"].ToString();
                strExcel = "  select * from [" + TableName + "]  ";
                myCommand = new OleDbDataAdapter(strExcel, strConn);
                myCommand.Fill(dt);


                if (dt.Rows.Count == 0 || dt.Columns.Count != 6) continue;

                if (ReturnDt.Rows.Count == 0)
                    ReturnDt = dt.Clone();
                Assembly(ReturnDt, dt);

            }
            //从指定的表明查询数据,可先把所有表明列出来供用户选择
            conn.Close();

            ReturnDt.Columns[0].ColumnName = "UpdateDate";
            ReturnDt.Columns[1].ColumnName = "UpdatePerson";
            ReturnDt.Columns[2].ColumnName = "UrlPath";
            ReturnDt.Columns[3].ColumnName = "UpdateContent";
            ReturnDt.Columns[4].ColumnName = "UpdateDesc";
            ReturnDt.Columns[5].ColumnName = "UpdateRemark";

            return ReturnDt;
        }

        private static DataTable Assembly(DataTable ReturnDt, DataTable dt_Data)
        {
            //将数据源中的表头去掉
            for (int i = 0; i < dt_Data.Rows.Count; i++)
            {
                DataRow dr = dt_Data.Rows[i];
                DataRow drNew = ReturnDt.NewRow();
                //赋值ReturnDt
                for (int j = 0; j < dt_Data.Columns.Count; j++)
                {
                    if (dr[j] != DBNull.Value && dr[j] != null)
                    {
                        drNew[j] = dr[j].ToString();
                    }
                }
                //将新行添加进表头表
                ReturnDt.Rows.Add(drNew);
            }
            return ReturnDt;
        }


        /// <summary>
        /// 获取文件的哈希值
        /// 用于判断文件是否改变
        /// </summary>
        /// <param name="FilePath">Excel路径</param>
        /// <returns></returns>
        public static String GetHashCode(String FilePath)
        {
            if (!File.Exists(FilePath)) return String.Empty;

            FileStream fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read);

            System.Security.Cryptography.HashAlgorithm algorithm;
            algorithm = System.Security.Cryptography.MD5.Create();
            byte[] buffer = algorithm.ComputeHash(fs);

            return BitConverter.ToString(buffer).Replace("-", "");

        }


        public static UpdateInfo[] GetUpdateInfo(List<FileInfo> li, String XmlFile)
        {
            String ExcelPath = String.Empty;
            DataTable dt;
            List<UpdateInfo> li_Update = new List<UpdateInfo>();
            List<PathInfo> li_PathInfo;
            XmlDocument Doc = XmlOpera.LoadXmlDoc(XmlFile);
            foreach (FileInfo item in li)
            {

                ExcelPath = item.Directory + @"\" + item.Name;

                //检验HashCode是否能匹配上XML中的文件信息GetFileInfo.GetHashCode(ExcelPath);

                if (CheckHashcode(item, XmlFile)) continue;

                dt = GetFileInfo.ReadEcxelData(ExcelPath);

                for (int i = 0; i < dt.Rows.Count; )
                {
                    if (dt.Rows[i]["UpdateContent"] != null && !string.IsNullOrEmpty(dt.Rows[i]["UpdateContent"].ToString()))
                    {
                        UpdateInfo ui = new UpdateInfo();
                        ui.UpdateDate = dt.Rows[i]["UpdateDate"].ToString();
                        ui.UpdatePerson = dt.Rows[i]["UpdatePerson"].ToString();
                        ui.UpdateContent = dt.Rows[i]["UpdateContent"].ToString();
                        ui.UpdateDesc = dt.Rows[i]["UpdateDesc"].ToString();
                        ui.UpdateRemark = dt.Rows[i]["UpdateRemark"].ToString();
                        li_PathInfo = new List<PathInfo>();

                        PathInfo pathInfo = new PathInfo();
                        if (dt.Rows[i]["UrlPath"] != null && !string.IsNullOrEmpty(dt.Rows[i]["UrlPath"].ToString()))
                        {
                            pathInfo.UrlPath = dt.Rows[i]["UrlPath"].ToString().Replace("/", @"\").Replace(@"\r", "").Replace(@"\n", "");
                            li_PathInfo.Add(pathInfo);
                            i++;
                        }


                        if (dt.Rows.Count == i)
                        {
                            ui.Path = li_PathInfo.ToArray();
                            li_Update.Add(ui);
                            continue;
                        }

                        while (dt.Rows[i]["UpdateContent"] == null || string.IsNullOrEmpty(dt.Rows[i]["UpdateContent"].ToString()))
                        {
                            PathInfo pathInfos = new PathInfo();
                            if (dt.Rows[i]["UrlPath"] != null && !string.IsNullOrEmpty(dt.Rows[i]["UrlPath"].ToString()))
                            {
                                pathInfos.UrlPath = dt.Rows[i]["UrlPath"].ToString().Replace("/", @"\").Replace(@"\r", "").Replace(@"\n", "");
                                li_PathInfo.Add(pathInfos);
                            }
                            i++;
                            if (dt.Rows.Count == i) break;
                        }
                        ui.Path = li_PathInfo.ToArray();
                        li_Update.Add(ui);
                    }
                }
                XmlOpera.SaveXmlData(Doc, XmlFile, li_Update, item);
                li_Update.Clear();
            }
            Doc.Save(XmlFile);

            return li_Update.ToArray();
        }

        /// <summary>
        /// 检验Excel文件是否在Xml文档中存在,或者已经更改
        /// </summary>
        /// <param name="ExcelFile"></param>
        /// <param name="XmlFile"></param>
        /// <returns></returns>
        private static bool CheckHashcode(FileInfo ExcelFile, string XmlFile)
        {
            String HashCode = GetFileInfo.GetHashCode(ExcelFile.Directory + "/" + ExcelFile.Name);
            FileInfo_Mo[] fileinfos = XmlOpera.ReadFileInfoFromXml(XmlFile);

            FileInfo_Mo[] Temp_FileInfo = fileinfos.Where(th => th.FileName == ExcelFile.Name).ToArray();

            if (0 == Temp_FileInfo.Count())
            {
                //插入文件信息到XML表中
                FileInfo_Mo item = new FileInfo_Mo();
                item.FileName = ExcelFile.Name;
                item.HasCode = HashCode;
                item.CreateDate = ExcelFile.CreationTime;
                XmlOpera.InSerFileInfoToXml(XmlFile, item);
                return false;
            }
            if (String.Compare(Temp_FileInfo[0].HasCode, HashCode) != 0)
            {
                //修改指定节点的HashCode
                XmlOpera.UpdateXmlFileInfo(XmlFile, ExcelFile.Name, HashCode);
                return false;
            }
            return true;
        }
    }
}
